package foundation.common.util;

import static foundation.zk.crud.composer.AbstractCRUDEditComposer.CALLBACK_ARGUMENT;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.proxy.HibernateProxyHelper;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.HtmlMacroComponent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Caption;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Row;
import org.zkoss.zul.api.Grid;
import org.zkoss.zul.api.Intbox;
import org.zkoss.zul.api.Label;
import org.zkoss.zul.api.Longbox;
import org.zkoss.zul.api.Paging;
import org.zkoss.zul.api.Textbox;
import org.zkoss.zul.api.Window;

import foundation.web.flow.AbstractPagingComposer;
import ar.com.sne.util.StringUtil;
public class FiltroBusquedaMacro extends HtmlMacroComponent {

	private static final long serialVersionUID = 1L;

	private final Log log = LogFactory.getLog(getClass());
	
	
	public Grid tabla;
	
	private  Label prop1;
	
	private  Label prop2;
	
	private  Label entidad;
	
	private Label labelProperty;
	
	private Label valueProperty1;
	private Label valueProperty2;
	
	private Textbox valPropiedad1;
	
	private Textbox valPropiedad2;
	
	private Boolean ocultarBotonLimpiar;
	
	private ValueImage insideSearch;
	
	private ValueImage insideClear;
	
	Row row;
	
	private String strEntidadComposer="";
	
	private String strEntidad="";
	
	private Window window;
	
	private GenericForwardComposer composer;
	
	private Map<String, Object> addFilters= new HashMap<String, Object>();
	
	private List<OrderFilter> addOrders= new ArrayList<OrderFilter>();
	
	private Boolean disabled=false;
	
	private Boolean noBuscarPreviamente=false;
	
	private EventListener eventToValidateSelectElement = null; // evento que si esta cargado al seleccionar un elemeto llama al ese callback para realizar validaciones sobre el elemento seleccoinar

	private Object selectedObject;
	
	private Caption captionTituloFiltroEntidad;
	
	private String tituloFiltroEntidad;
	
	public List<OrderFilter> getAddOrders() {
		return addOrders;
	}


	public void setAddOrders(List<OrderFilter> addOrders) {
		this.addOrders = addOrders;
	}


	public Map<String, Object> getAddFilters() {
		return addFilters;
	}


	public void setAddFilters(Map<String, Object> addFilters) {
		this.addFilters = addFilters;
	}
	
	public void addExtraFilter(String key, Object value){
		if(addFilters==null)
			addFilters=new HashMap<String, Object>();
		addFilters.put(key, value);
	}
	
	public void addAllExtraFilter(Map<String, Object> parametros){
		if(addFilters==null)
			addFilters=new HashMap<String, Object>();
		addFilters.putAll(parametros);
	}
	
	public void addExtraOrder(OrderFilter orderFilter){
		if(addOrders==null)
			addOrders=new ArrayList<OrderFilter>();
		addOrders.add(orderFilter);
	}

	@Override
	public void afterCompose() {
		super.afterCompose(); // DON'T forget this
		
		
		instanciarComponentes();
		
		insideClear.addEventListener(Events.ON_CLICK, new EventListener() {
            public void onEvent(Event event) throws Exception {
            	clearFilters();
               
            }
        });
		
		try{
			updateComponentes(null);
		}catch(Exception e){
			log.error(e.getMessage());
		}
		
		insideSearch = (ValueImage)tabla.getFellow("insideSearch");
		
		insideSearch.addEventListener(Events.ON_CLICK, new EventListener() {
				            public void onEvent(Event event) throws Exception {				         
				            	searchEntity();	
				          }});
		
		if(valPropiedad1!=null){			
			valPropiedad1.addEventListener(Events.ON_OK, new EventListener() {
	            public void onEvent(Event event) throws Exception {				         
	            	searchEntity();				               
	            }
	        });	
		}		
		if(valPropiedad2!=null){
			valPropiedad2.addEventListener(Events.ON_OK, new EventListener() {
	            public void onEvent(Event event) throws Exception {				         
	            	searchEntity();				               
	            }
	        });	
		}		
		
		//captionTituloFiltroEntidad= (Caption)getFellowIfAny("captionTituloFiltroEntidad");
		captionTituloFiltroEntidad=(Caption)((Row)tabla.getRowsApi().getChildren().get(1)).getFirstChild().getChildren().get(0);
		if(captionTituloFiltroEntidad!=null && !StringUtil.isNullOrEmpty(tituloFiltroEntidad)){
			captionTituloFiltroEntidad.setLabel(tituloFiltroEntidad);
		}
	}
	
	
	public void searchEntity(){
		try {
			
			
		String strEntity = strEntidad.substring(0, 1).toLowerCase()+strEntidad.substring(1);
    	String strService = strEntity+"Service";
    	
        valPropiedad1 = (Textbox)tabla.getFellow("valPropiedad1");
           
        try{
        valPropiedad2 = (Textbox)tabla.getFellow("valPropiedad2");
        }
        catch (Exception e) {
			valPropiedad2=null;
		}
          
//        Object service = CommonWebUtil.getService(strService);
           
        FinderFilter ff=new FinderFilter();
        
        
        //agrego los filtros pasados como parametros
        if(addFilters!=null){
        	for(String key: addFilters.keySet()){
        		ff.addFilter(key, addFilters.get(key));
        	}
        }
        
        //agrego los orders pasados como parametros
        if(addOrders!=null){
        	for(OrderFilter orderFilter: addOrders){
        		ff.addOrder(orderFilter);
        	}
        }
        
        String val1="";
        String val2="";
        
        
        if(!StringUtil.isNullOrEmpty(valPropiedad1.getValue())){
        	val1=valPropiedad1.getValue();
        	ff.addFilter(prop1.getValue(), val1);
        }
           
           
        if(valPropiedad2!=null && !StringUtil.isNullOrEmpty(valPropiedad2.getValue())){
        	val2 = valPropiedad2.getValue();
           ff.addFilter(prop2.getValue(), val2);
        }
        
        
        String modoSeleccion =(String)getDynamicProperty("modoSeleccion");
        if( !StringUtil.isNullOrEmpty(modoSeleccion)){
        	String strModoSeleccion = modoSeleccion;
    		ff.addFilter(CommonGeneralUtil.MODOSELECCION,modoSeleccion);
        	
        }
         
      
//        Class serviceClass = service.getClass();
        List<Object>listResult = new ArrayList<Object>();
        if(!noBuscarPreviamente){
//	        if(!StringUtil.isNullOrEmpty(val1 + val2))
//	        	listResult = (List<Object>)serviceClass.getMethod("find", FinderFilter.class).invoke(service, ff);
	        
        }
        String strLabelProperty = labelProperty.getValue();
        
       
        String setter = "set"+(StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer);
        String getter = "get"+(StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer);
        
        Object objAnterior =null;
        if(composer!=null){
        	invokeGetter(composer, getter);
        }
        else{
        	objAnterior=selectedObject;
        }
        
        Object[] arrayObjects = {null};
        if(objAnterior != null && composer!=null){
        	Executions.getCurrent().getDesktop().setAttribute("selectedObject", objAnterior);
        	composer.getClass().getMethod(setter, objAnterior.getClass()).invoke(composer, arrayObjects);
        }
        	

        if(listResult.size()==1){
        	Object objectToSet = listResult.get(0);
        	if(composer!=null){
        		invokeSetter(composer, setter, objectToSet);
        	}
        	else{
        		selectedObject=objectToSet;
        	}
        	updateComponentes(objectToSet);
        	lanzarAvisoCambio(objectToSet);

        }else{					            	
        	String redirectZUL =CommonWebUtil.getProperty("seleccion" + strEntidad);
        	Map<String, Object> args = new HashMap<String, Object>();
    		args.put(CALLBACK_ARGUMENT, new EventListener() {
//    			@Override
    			public void onEvent(Event event) throws Exception {
    				checkSelected(event);
    			}
    		});					        		
    		if(modoSeleccion!=null)
    			args.put(CommonGeneralUtil.MODOSELECCION,modoSeleccion);					        		
    		

    		Window winAdd = (Window) Executions.createComponents(redirectZUL, window,
    				args);
    		
    		
    		String prop1winAdd = "tbox"+prop1.getValue().substring(0,1).toUpperCase()+prop1.getValue().substring(1);
    		
    		
    		Textbox tb1 = (Textbox)winAdd.getFellowIfAny(prop1winAdd);
    		if(tb1 != null)
    			tb1.setValue(valPropiedad1.getValue());
    		
    		
    		
    		if(!StringUtil.isNullOrEmpty(prop2.getValue())){
    			Textbox tb2;
    			String prop2winAdd =  "tbox"+prop2.getValue().substring(0,1).toUpperCase()+prop2.getValue().substring(1);
    			tb2 = (Textbox)winAdd.getFellowIfAny(prop2winAdd);
    			if(tb2 != null && valPropiedad2!=null){
    				tb2.setValue(valPropiedad2.getValue());
    			}
    		}
    		
    		Map<String,Object> addExtraFiltersNoInView= new HashMap<String, Object>();
    		
    		if(addFilters!=null){
            	for(String key: addFilters.keySet()){
            		Longbox lb;
            		String lId= "lbox"+key.substring(0,1).toUpperCase()+key.substring(1);
            		lb = (Longbox)winAdd.getFellowIfAny(lId);
            		if(lb != null){
            			lb.setValue((Long)addFilters.get(key));
            			lb.setDisabled(true);
            			continue;
            		}
            		
               		Intbox ib;
            		String iId= "ibox"+key.substring(0,1).toUpperCase()+key.substring(1);
            		ib = (Intbox)winAdd.getFellowIfAny(iId);
            		if(ib != null){
            			ib.setValue((Integer)addFilters.get(key));
            			ib.setDisabled(true);
            			continue;
            		}
            		        
            		
            		
//            		ComboBoxEnum cbbEnum;
//            		String strParamEnum =key.substring(0,1).toUpperCase()+key.substring(1);
//            		String cbbEnumId ="cbb"+strParamEnum;
//            		Object object =winAdd.getFellowIfAny(cbbEnumId);
//            		if(object instanceof ComboBoxEnum){
//            			cbbEnum = (ComboBoxEnum)object;
//                		if(cbbEnum != null){
//                			Object parameterObject=addFilters.get(key);
//                			cbbEnum.setObjectSelect(parameterObject);
//                			cbbEnum.setDisabled(true);
//                			continue;
//                		}
//                		
//            		}
            		
             		Checkbox checkbox;
            		String chkId= "chk"+key.substring(0,1).toUpperCase()+key.substring(1);
            		checkbox = (Checkbox)winAdd.getFellowIfAny(chkId);
            		if(checkbox != null){
            			checkbox.setChecked((Boolean)addFilters.get(key));
            			checkbox.setDisabled(true);
            			continue;
            		}
            	         
            		
            		
               		Textbox tb;
            		String tbId= "tbox"+key.substring(0,1).toUpperCase()+key.substring(1);
            		tb = (Textbox)winAdd.getFellowIfAny(tbId);
            		if(tb != null){
            			tb.setValue((String)addFilters.get(key));
            			tb.setDisabled(true);
            			continue;
            		}
            		
		           		
  
            	            	           		
//            		ComboBoxEntity cbb;
//            		String strParamEntity =key.substring(0,1).toUpperCase()+key.substring(1);
//            		String cbbId ="cbb"+strParamEntity;
//            		cbb = (ComboBoxEntity)winAdd.getFellowIfAny(cbbId);
//            		if(cbb != null){
//            			Object parameterObject=addFilters.get(key);
//            			String strParamService = strParamEntity.substring(0,1).toLowerCase()+strParamEntity.substring(1)+"Service";
////            			Object paramService = CommonWebUtil.getService(strParamService);
////            			AbstractPersistentObject abstractObject = (AbstractPersistentObject)parameterObject;
////            			parameterObject = paramService.getClass().getMethod("findById", Long.class).invoke(paramService, abstractObject.getId());
//            			
//            			cbb.setObjectSelect(parameterObject);
//            			cbb.setDisabled(true);
//            			continue;
//            		}
//            		
            		
            		
            		FiltroBusquedaMacro filtroBusqueda;
            		String filtroBusquedaid= "filtroEntidad"+key.substring(0,1).toUpperCase()+key.substring(1);
            		filtroBusqueda = (FiltroBusquedaMacro)winAdd.getFellowIfAny(filtroBusquedaid);
            		if(filtroBusqueda != null){
            			filtroBusqueda.selectedObject(addFilters.get(key), addFilters.get(key).getClass());            			
            			filtroBusqueda.setDisabled(true);
            			continue;
            		}            		
            		
            		//si no es una filtro de vista, es un filtro por atras.
            		addExtraFiltersNoInView.put(key,addFilters.get(key));
            	}
            }
    		Object composer =winAdd.getAttribute(winAdd.getId()+"$composer");
    		if(composer instanceof AbstractPagingComposer)
    		{
    			AbstractPagingComposer composerPaging =(AbstractPagingComposer)composer;
    			if(addExtraFiltersNoInView.keySet().size()>0){
    				composerPaging.setAddExtraFilters(addExtraFiltersNoInView);
    				composerPaging.setAddExtraOrders(addOrders);
    			}
    			try{
    				if(!noBuscarPreviamente){
    					if(listResult!=null && listResult.size()>0){
    						List subList =new ArrayList();
    						int pagsize=12;
    						
    						Paging paging = (Paging) winAdd.getFellowIfAny("paging");
    						if(paging!=null){
    							pagsize=paging.getPageSize();
    							paging.setTotalSize(listResult.size());
    						}
    						if(listResult.size()>pagsize){    							
    							subList =listResult.subList(0,pagsize);
    						}
    						else{
    							subList =listResult;
    						}	    						
    		        		Grid grid = (Grid) winAdd.getFellowIfAny("grdSearchResult");
    		        		if(grid != null){
    		        			ListModelList lm = new ListModelList(subList);
    		        			grid.setModel(lm);
    		        		}    
    					}

    				}
    			}catch (Exception e) {
    				winAdd.detach();
				}

    		}
    		else {
        		Grid grid = (Grid) winAdd.getFellowIfAny("grdSearchResult");
        		if(grid != null){
        			ListModelList lm = new ListModelList(listResult);
        			grid.setModel(lm);
        		}       		
    		}

    		Executions.getCurrent().getDesktop().setAttribute(((GenericForwardComposer)winAdd.getAttribute(winAdd.getId()+"$composer")).getClass().getSimpleName(), winAdd);
    		
    		try {

    			winAdd.doModal();
    		} catch (Exception e) {
    			log.error("Error opening modal EDIT window", e);
    			log.error(e.getMessage());
    		    throw new RuntimeException(e);
    		    
    		}
        }
		} catch (InvocationTargetException ite) {
			Throwable targetException = ite.getTargetException();
			// propaga las BusinessException tiradas por el composer
			if ( targetException instanceof BusinessException ) {
				throw (BusinessException) ite.getTargetException();
			} else {
				log.error(targetException);		
			}
		} catch (Exception e) {
			log.error(e);
		}
	}
	
	public Object checkSelected(Event event) throws Exception{
		Object selectedObject = Executions.getCurrent().getDesktop().getAttribute("selectedObject");
		if (selectedObject != null){
			
			if(eventToValidateSelectElement!=null){
				eventToValidateSelectElement.onEvent(event);
			}
			if(composer!=null){
				String setter = "set"+(StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer);			 
				invokeSetter(composer, setter, selectedObject);
			}
			else{
				this.selectedObject=selectedObject;				
			}
			updateComponentes(selectedObject);			
			lanzarAvisoCambio(selectedObject);
		}
		
		Executions.getCurrent().getDesktop().removeAttribute("selectedObject");
		return selectedObject;
	}
	
	
	public Object updateComponentes(Object objectToSet) throws Exception {
		
		Object invokeObject= null;
		if(composer!=null){
			invokeObject=composer;		
			String strEntidad=entidad.getValue();			
			String getterEntidad = "get"+(StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer).substring(0,1).toUpperCase()+(StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer).substring(1);			
			invokeObject=invokeGetter(invokeObject, getterEntidad);
		}
		else{
			invokeObject=objectToSet;
		}
		if(invokeObject==null){
			if(valPropiedad2==null)
				valueProperty1.setValue("");
			else
				valueProperty2.setValue("");
			return invokeObject;
		}
		
		valPropiedad1.setValue(getStrValue(prop1.getValue(), invokeObject));
		
		if(valPropiedad2!=null)
			valPropiedad2.setValue(getStrValue(prop2.getValue(), invokeObject));
		
		
		if(valPropiedad2==null)
			valueProperty1.setValue(getStrValue(labelProperty.getValue(),invokeObject));
		else
			valueProperty2.setValue(getStrValue(labelProperty.getValue(),invokeObject));
		
		
		return invokeObject;	
	}
	
	public String getStrValue(String strPropiedad, Object entidad) throws Exception{
		List<String>listPropiedades = new ArrayList<String>();
		if(!StringUtil.isNullOrEmpty(strPropiedad)){
			while(strPropiedad.indexOf(".")>0){
				listPropiedades.add(strPropiedad.substring(0,strPropiedad.indexOf(".")));
				strPropiedad = strPropiedad.substring(strPropiedad.indexOf(".")+1);
			}
			
			//Agrego la propiedad que quedo sin punto
			listPropiedades.add(strPropiedad);
			
			
			for (String prop:listPropiedades){
				
				String getter = "get"+prop.substring(0,1).toUpperCase()+prop.substring(1);
				entidad=invokeGetter(entidad, getter);
				if(entidad == null)
					break;
			}
			String strValue="";
			if(entidad != null ){
				if(entidad.getClass().getSimpleName().equals(String.class.getSimpleName()))
					return (String)entidad;
				else if(entidad.getClass().getSimpleName().equals(Long.class.getSimpleName()))
					return ((Long)entidad).toString();
				else if(entidad.getClass().getSimpleName().equals(Integer.class.getSimpleName()))
					return ((Integer)entidad).toString();
				
			}
		}
		
		return "";
	}
	
	
	
	public Object invokeGetter(Object object, String methodName) throws Exception{
		Class objectClass = object.getClass();
		return (Object)objectClass.getMethod(methodName).invoke(object);
	}
	
	public Object invokeSetter(Object object, String methodName, Object parameter) throws Exception{
		Class objectClass = object.getClass();
		 Object objectReturn =(Object)objectClass.getMethod(methodName,parameter.getClass()).invoke(object, parameter);
		 //notifico que sette el un objeto
		 return objectReturn;
	}

	public Object invokeSetter(Object object, String methodName, Object parameter, Class clase) throws Exception{
		Class objectClass = object.getClass();
		return (Object)objectClass.getMethod(methodName,clase).invoke(object, parameter);
	}
	
	public void instanciarComponentes(){
		
		if(composer==null){
			composer = (GenericForwardComposer) Executions.getCurrent().getDesktop().getAttribute("composer");	
		}
	
		tabla = (Grid) getFellow("tabla");
		
		//row = (Row) tabla.getParent().getParent();
		Component comp=(Component)tabla;
		if(row ==null){
			while (comp.getParent() !=null){
				comp = (Component)comp.getParent();
				if (comp.getClass().equals(Row.class)){
					row=(Row)comp;
					break;
				}
			}
			
		}
		
		Grid tablaPadre = (Grid) row.getParent().getParent();
		
		entidad = (Label) tabla.getFellow("entidad");
		
		prop1 = (Label)tabla.getFellow("prop1");
		
		if(tabla.getFellow("prop2")!=null)
			prop2 = (Label)tabla.getFellow("prop2");		
		
		labelProperty = (Label)tabla.getFellow("labelProperty");
		

		valPropiedad1 =  (Textbox)tabla.getFellow("valPropiedad1");
		String maxLengthP1 = (String)getDynamicProperty("maxlengthPropiedad1");
		if(!StringUtil.isNullOrEmpty(maxLengthP1) && StringUtil.isNumeric(maxLengthP1)){
			valPropiedad1.setMaxlength(new Integer(maxLengthP1));
		}
		
		try{
		valPropiedad2 =  (Textbox)tabla.getFellow("valPropiedad2");
		String maxLengthP2 = (String)getDynamicProperty("maxlengthPropiedad2");
		if(!StringUtil.isNullOrEmpty(maxLengthP2) && StringUtil.isNumeric(maxLengthP2)){
			valPropiedad2.setMaxlength(new Integer(maxLengthP2));
		}
		}
		catch (Exception e) {
			valPropiedad2 =  null;
		}
		
		
		if(valPropiedad2==null)
			valueProperty1 = (Label)tabla.getFellowIfAny("valueProperty1");
		else
			valueProperty2 = (Label)tabla.getFellowIfAny("valueProperty2");
		
		
		
		insideClear = (ValueImage) tabla.getFellow("insideClear");
		
		if( ocultarBotonLimpiar!=null &&  ocultarBotonLimpiar && this.insideClear!=null){
			this.insideClear.setVisible(false);
		}
		
		strEntidad=entidad.getValue();
		strEntidadComposer=(String) this.getDynamicProperty("entidadComposer");
		
		comp = (Component)tabla;
		
		List<Component>listComp = new ArrayList<Component>();
		//estan quedando la lista referenciando a un mismo objeto
		if(window ==null){
			while (comp.getParent() !=null){
				comp = (Component)comp.getParent();
				if (comp.getClass().equals(Window.class)){
					window=(Window)comp;
					break;
				}
			}
			
		}
		
		addFilters = (HashMap<String,Object>)this.getDynamicProperty("addFilters");
		
		row.setSpans(new Integer(tablaPadre.getColumnsApi().getChildren().size()).toString());
		
		Row primeraFila = (Row) tabla.getRowsApi().getChildren().get(0);
		primeraFila.setSpans(new Integer(tabla.getColumnsApi().getChildren().size()).toString());
	}
	
	
	
	public void selectedObject(Object selectedObject, Class clase){		
		try {
		if (selectedObject != null){		
			this.selectedObject=selectedObject;
			if(composer!=null){
				String setter = "set"+(StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer);
				invokeSetter(composer, setter, selectedObject,clase);
			}
			updateComponentes(selectedObject);
		}		
		Executions.getCurrent().getDesktop().removeAttribute("selectedObject");
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}
	
	public Object getSelectedObject(){
		if(composer!=null){
			String getter = "get"+(StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer);
			Object o=null;
			try {
				o = invokeGetter(composer, getter);
			} catch (Exception e) {
				// TODO Auto-generated catch block			
				log.error(e.getMessage());
			}
			return o;
		}
		return selectedObject;
	}
	

	public void clearFilters() {
		try {
    	String strEntidad = entidad.getValue();
    	strEntidad = strEntidad.substring(0, 1).toLowerCase()+strEntidad.substring(1);
    	String strService = strEntidad+"ServiceImpl";
           
        valPropiedad1.setValue("");
           
        if(valPropiedad2!=null)
        	valPropiedad2.setValue("");
        
        
        if(valPropiedad2==null)
        	valueProperty1.setValue("");
		else
			valueProperty2.setValue("");
        
        strEntidad=StringUtil.isNullOrEmpty(strEntidadComposer)?strEntidad:strEntidadComposer;
        strEntidad=strEntidad.substring(0, 1).toUpperCase()+strEntidad.substring(1);
        String setter = "set"+strEntidad;
        String getter = "get"+strEntidad;
        
        Object objAnterior;
		if(composer!=null){
			objAnterior = invokeGetter(composer, getter);
		}
		else{
			objAnterior=selectedObject;
		}
	
        Class parameterClass=null;
        if(objAnterior!=null){
        	parameterClass = objAnterior.getClass();
            String nombreClase = objAnterior.getClass().getName();
            if(objAnterior.getClass().getName().indexOf("_$$_javassist")>0){
            	nombreClase = nombreClase.substring(0,nombreClase.indexOf("_$$_javassist"));
            	parameterClass = Class.forName(nombreClase);
            }
        }
        
        Object[] arrayObjects = {null};
        if(objAnterior != null)
        	if(composer!=null){
        		composer.getClass().getMethod(setter, parameterClass).invoke(composer, arrayObjects);
        	}
        lanzarAvisoCambio(null);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	public Boolean getOcultarBotonLimpiar() {
		return ocultarBotonLimpiar;
	}

	public void setOcultarBotonLimpiar(Boolean ocultarBotonLimpiar) {
		this.ocultarBotonLimpiar = ocultarBotonLimpiar;
	}
	
	public void setDisabled(boolean disabled){
		this.disabled=disabled;
		if(disabled){
			if(valPropiedad1!=null)
				valPropiedad1.setDisabled(true);
			if(valPropiedad2!=null)
				valPropiedad2.setDisabled(true);
			insideSearch.setVisible(false);
			insideClear.setVisible(false);
			instanciarComponentes();
		}
		else{
			if(valPropiedad1!=null)
				valPropiedad1.setDisabled(false);
			if(valPropiedad2!=null)
				valPropiedad2.setDisabled(false);
			insideSearch.setVisible(true);
			insideClear.setVisible(true);
			instanciarComponentes();
		}
	}


	public GenericForwardComposer getComposer() {
		return composer;
	}


	public void setComposer(GenericForwardComposer composer) {
		this.composer = composer;
	}


	public Boolean getDisabled() {
		return disabled;
	}




	public Boolean getNoBuscarPreviamente() {
		return noBuscarPreviamente;
	}


	public void setNoBuscarPreviamente(Boolean noBuscarPreviamente) {
		this.noBuscarPreviamente = noBuscarPreviamente;
	}


	public EventListener getEventToValidateSelectElement() {
		return eventToValidateSelectElement;
	}


	public void setEventToValidateSelectElement(
			EventListener eventToValidateSelectElement) {
		this.eventToValidateSelectElement = eventToValidateSelectElement;
	}

	
//	public void setLabelProperty1(String label){
//		LabelCampoComposer labelProperty1 = (LabelCampoComposer)tabla.getFellow("labelProperty1");
//		labelProperty1.setValue(label);
//	}


	public void setSelectedObject(Object selectedObject) {
		this.selectedObject = selectedObject;
		if(selectedObject!=null){
			selectedObject(selectedObject,HibernateProxyHelper.getClassWithoutInitializingProxy(selectedObject));
		} 
		else{
			selectedObject(null, null);
		}
	}


	
	
	

	private void lanzarAvisoCambio(Object objectToSet){
		 Events.sendEvent(new Event(Events.ON_NOTIFY, this,objectToSet));
		 Events.sendEvent(new Event(Events.ON_CHANGE, this,objectToSet));
	}


	public void setTituloFiltroEntidad(String tituloFiltroEntidad) {
		this.tituloFiltroEntidad = tituloFiltroEntidad;
		if(captionTituloFiltroEntidad!=null && !StringUtil.isNullOrEmpty(tituloFiltroEntidad)){
			captionTituloFiltroEntidad.setLabel(tituloFiltroEntidad);
		}
	}


	public String getTituloFiltroEntidad() {
		return tituloFiltroEntidad;
	}
}
